package com.gensdai.leliang.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bluelinelabs.logansquare.LoganSquare;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.common.bean.ProvinceJsonBean;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.Address;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.utils.GetJsonDataUtil;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/2.
 */

public class New_delivery_address extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.collect_man)
    EditText collect_Man;
    @BindView(R.id.phone_number)
    EditText phone_Number;
    @BindView(R.id.province)
    TextView province;
    @BindView(R.id.details)
    EditText details;
    @BindView(R.id.provinceLayout)
    LinearLayout provinceLayout;

    private Upload up;
    SharedPreferences share;
    SharedPreferences.Editor ed;
    private Address address = null;
//    private String[] city; // 选择后的城市地方集合
//    TextView mCurrentProviceName_t, mCurrentCityName_t, mCurrentDistrictName_t;

    private final int ENTER = 2;
    private final int SELECT = 1;

    private Thread thread;
    private static final int MSG_LOAD_DATA = 90001;
    private static final int MSG_LOAD_SUCCESS = 90002;
    private static final int MSG_LOAD_FAILED = 90003;
    private boolean isLoaded = false;

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {

//                            user = (UserNameBean) new json_base().jsonEnter(new JSONObject((String) msg.obj));
                            New_delivery_address.this.finish();
                        } else {

                        }
                        Toast.makeText(
                                New_delivery_address.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case SELECT:

//                    city = (String[]) msg.obj;
//                    mCurrentProviceName_t.setText(city[0]);
//                    mCurrentCityName_t.setText(city[1]);
//                    mCurrentDistrictName_t.setText(city[2]);
//                    invalidateOptionsMenu();

                    break;
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

//                        Toast.makeText(New_delivery_address.this, "开始解析数据", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(New_delivery_address.this, "解析数据成功", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(New_delivery_address.this, "解析数据失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_delivery_address);
        ButterKnife.bind(this);
        init();
    }

    /**
     * 初始化
     */
    private void init() {

        //开启数据解析
        handler.sendEmptyMessage(MSG_LOAD_DATA);
        //end

        uiTitle.setText(getString(R.string.new_collect_address));
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        up = new Upload(this);
        if (getIntent().hasExtra("address")) {
            uiTitle.setText(getString(R.string.editor_collect_address));
            address = (Address) getIntent().getSerializableExtra("address");
            collect_Man.setText(address.getUser_name());
            phone_Number.setText(address.getPhone());
            provinceStr = address.getProvinceId();
            cityStr = address.getCityId();
            districtStr = address.getDistrictId();
            province.setText(address.getProvinceId() + address.getCityId() + address.getDistrictId());
            details.setText(address.getAddress());
        }
        back.setOnClickListener(this);
        save.setOnClickListener(this);
//        province.setOnClickListener(this);
        provinceLayout.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.save:
                if (uiTitle.getText().toString().trim().equals(this.getString(R.string.new_collect_address))) {
                    AddressRequestStr();
                } else {
                    EditAddressRequestStr();
                }

                break;
            case R.id.province:

                break;
            case R.id.provinceLayout:

                hideKeyBoard(this, phone_Number);

                if (isLoaded) {
                    ShowPickerView();
                } else {
//                    Toast.makeText(New_delivery_address.this, "数据暂未解析成功，请等待", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }


    public String provinceStr;
    public String cityStr;
    public String districtStr;

    /**
     * 调用增加收货地址
     */
    private void AddressRequestStr() {
        //获取edit的值后请求

        String collectMan = collect_Man.getText().toString().trim();
        String phoneNumber = phone_Number.getText().toString().trim();
        String Province = province.getText().toString().trim();
        String Details = details.getText().toString().trim();


        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userId", share.getString("user_id", ""));   //用户id
        loginParams.put("provinceId", provinceStr);  //省
        loginParams.put("cityId", cityStr);  //市
        loginParams.put("districtId", districtStr);  //区
        loginParams.put("detailedAddress", Details);  //详情地址
        loginParams.put("phone", phoneNumber); //手机号
        loginParams.put("name", collectMan); //收货人

        Log.e("New_delivery_address", loginParams.get("provinceId"));
        Log.e("New_delivery_address", loginParams.get("detailedAddress"));
//        toStr(collectMan, share.getString("user_id", ""), Province, "", "", Details, phoneNumber);
        AddressRequestStr(loginParams);
    }

    //返回字符串类型
    private void AddressRequestStr(Map<String, String> loginParams) {
//    private void toStr(String name,
//                       String userId,
//                       String provinceId,
//                       String cityId,
//                       String districtId,
//                       String detailedAddress,
//                       String phone) {
        up.show();
        ApiService.getInstance(this).AddressRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 调用编辑收货地址----------------------------------------------------------------------
     */
    private void EditAddressRequestStr() {
        //获取edit的值后请求

        String collectMan = collect_Man.getText().toString().trim();
        String phoneNumber = phone_Number.getText().toString().trim();
        String Province = province.getText().toString().trim();
        String Details = details.getText().toString().trim();


        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userId", share.getString("user_id", ""));   //用户id
        loginParams.put("provinceId", provinceStr);  //省
        loginParams.put("addressId", address.getId());  //收货地址ID
        loginParams.put("cityId", cityStr);  //市
        loginParams.put("districtId",districtStr);  //区
        loginParams.put("detailedAddress", Details);  //详情地址
        loginParams.put("phone", phoneNumber); //手机号
        loginParams.put("name", collectMan); //收货人

        Log.e("userId", share.getString("user_id", ""));
        Log.e("addressId", address.getId());
        Log.e("New_delivery_address", loginParams.get("detailedAddress"));
//        EdittoStr(collectMan, share.getString("user_id", ""), Province, "", "", Details, phoneNumber, address.getId());
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
//    private void EdittoStr(String name,
//                           String userId,
//                           String provinceId,
//                           String cityId,
//                           String districtId,
//                           String detailedAddress,
//                           String phone,
//                           String addie) {
        up.show();
        ApiService.getInstance(this).EditAddressRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);

                province.setText(tx);
                provinceStr = options1Items.get(options1).getPickerViewText();
                cityStr = options2Items.get(options1).get(options2);
                districtStr = options3Items.get(options1).get(options2).get(options3);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceJsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCity().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCity().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCity().get(c).getArea() == null
                        || jsonBean.get(i).getCity().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCity().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCity().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    private ArrayList<ProvinceJsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    public ArrayList<ProvinceJsonBean> parseData(String result) {//lgansquare 解析
        ArrayList<ProvinceJsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            for (int i = 0; i < data.length(); i++) {
                ProvinceJsonBean entity = LoganSquare.parse(data.optJSONObject(i).toString(), ProvinceJsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


    /**
     * 隐藏系统键盘
     */
    public static void hideKeyBoard(Context ctx, View view) {
        InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}
